package flst.ipiweb.struts.action.administrateur;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import flst.ipiweb.proxy.ServiceAdministrateurProxy;
import flst.ipiweb.transverse.Administrateur;
import flst.ipiweb.transverse.IPIException;

public class ListAdminAction extends Action{

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		//On récupère la session
		HttpSession session = request.getSession();
		if(session.getAttribute("login") == null)
		{
			return mapping.findForward("login");
		}
		
		//Titre de la page
		request.setAttribute("pageTitle", "admin.list.title");
		//Activation de l'onglet administrateur
		HashMap<String, String> onglet = new HashMap<String, String>();
		onglet.put("administrateur", "active");
		request.setAttribute("onglet", onglet);
		
		//Instanciation du service administrateur
		ServiceAdministrateurProxy sAdministrateur = new ServiceAdministrateurProxy((Boolean) session.getAttribute("isSuper"));
		
		List<Administrateur> listAdmin;
		try {
			listAdmin = sAdministrateur.listAdministrateur();
			Collections.sort(listAdmin, new Comparator<Administrateur>() {
				public int compare(Administrateur admin1, Administrateur admin2){
					if(admin1.getIsSuper() != admin2.getIsSuper()){
						if(admin1.getIsSuper()){
							return -1;
						}
						return 1;
					}
					if(admin1.getIsSuper() == admin2.getIsSuper()){
						return admin1.getNom().compareToIgnoreCase(admin2.getNom());
					}
					return 0;
				}
			});
			
			Administrateur superAdmin = listAdmin.get(0);
			listAdmin.remove(0);
			request.setAttribute("superAdmin", superAdmin);
			request.setAttribute("listAdmin", listAdmin);
		
		} catch (IPIException e) {
			session.setAttribute("error",e.getMessage());
		}
		
		request.setAttribute("error",session.getAttribute("error"));
		request.setAttribute("success",session.getAttribute("success"));
		
		return mapping.findForward("list_admin");
	}

}
